<script setup>
import { onMounted, watch } from 'vue';
import { useRequestProvider } from 'vue-hooks-plus';
import { RouterView, useRouter } from 'vue-router';
import { ElConfigProvider } from 'element-plus';
import zhCn from 'element-plus/dist/locale/zh-cn.mjs';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import CommonAlertHub from './common/CommonAlertHub.vue';
import { useInitApp } from './common/js/common-useInitApp';
import RouterLoading from './components/RouterLoading.vue';
import { useAlarmCenterStore } from './stores/alarmCenter';
import useStompJsStore from './stores/webSocket';
import { clearToken } from './utils/auth';

// 全局配置 useRequestProvider
useRequestProvider({
  retryCount: 3, // 错误重试次数
  throttleWait: 1000, // 节流等待时间
  debounceWait: 1000, // 防抖等待时间
});

// dayjs国际化
dayjs.locale('zh-cn');

onMounted(() => {
  const router = useRouter();
  const { safeInit } = useInitApp();
  const alarmStore = useAlarmCenterStore();
  // 监听路由变化，尝试初始化
  let stopWatch;

  stopWatch = watch(
    () => router.currentRoute.value.path,
    async () => {
      // 如果已在登录页或首页（公共页），不初始化
      if (['/login', '/'].includes(router.currentRoute.value.path)) {
        return;
      }

      const success = await safeInit();

      if (!success) {
        clearToken();
        alarmStore.clearAll(); // 清空告警
        router.replace('/login');
      }

      stopWatch(); // 执行一次后解绑
    },
    { immediate: true },
  );

  // 路由跳转时管理 STOMP（可选）
  router.afterEach((to) => {
    const stompJsStore = useStompJsStore();

    if (['/login', '/'].includes(to.path)) {
      stompJsStore.setDeActivate();
    }
  });

  // 退出登录时清空告警（可选增强）
  router.beforeEach((to) => {
    if (to.name === 'Login' || to.path === '/login') {
      alarmStore.clearAll();
    }
  });
});
</script>

<template>
  <ElConfigProvider :locale="zhCn">
    <!-- <Suspense> -->
    <template #default>
      <RouterView v-slot="{ Component }">
        <!-- <Transition :name="route.meta.transitionName" mode="out-in"> -->
        <Component :is="Component" />
        <!-- </Transition> -->
      </RouterView>
    </template>
    <template #fallback>
      <RouterLoading />
    </template>
    <!-- </Suspense> -->
  </ElConfigProvider>
  <!-- 全局告警中心 -->
  <CommonAlertHub />
</template>
